<?php
class Core_Component_Account_Model_Group extends Soul_Model_Entity_Base {

	protected $tableName = '{t}account_group';
	
    public function validate() {
        if ($this->isNew()) {
        	if ($this->checkExists(array('code'=>$this->getCode()))) {
            	throw new Core_Component_Account_Exception(Core_Component_Account_Exception::GROUP_REPEATED);
            }
        }
        return parent::validate();
    }
    
    public function getAccounts(){
    	return App::getModel('account/account')->getQuery()
    				->where('`group_id`=:group:i')
    				->addParameter('group', $this->getId());
    }
    
    public function delete() {
        $ids = Soul_Util_Array::pack($ids);
        Soul_Db_Factory::createDelete()
            ->delete('{t}account_account_group')
            ->condition('group_id', $this->id)
            ->execute($this->getDb());
        parent::delete();
    }
    
    public function deleteBatch(array $ids) {
        Soul_Db_Factory::createDelete()
            ->delete('{t}account_account_group')
            ->condition('group_id', $ids, 'in')
            ->execute($this->getDb());
        parent::deleteBatch($ids);
    }
    
    protected function beforeInsert() {
        $this->updateLanguageFile();
        parent::beforeInsert();
    }
    
    protected function beforeUpdate(){
        $this->updateLanguageFile();
        parent::beforeUpdate();
    }
    
    private function updateLanguageFile(){
        $bus = App::getBusiness('system/localize');
        $bus->writeLanguageFile('account.group.'.$this->getCode(), $this->getName());
        $bus->writeLanguageFile('account.group.'.$this->getCode().'_desc', $this->getDescription());
        $this->setName('account.group.'.$this->getCode())
             ->setDescription('account.group.'.$this->getCode().'_desc');
    }     

    protected function initializeProperties() {
        $this->createProperty('id', 'integer', TRUE, TRUE);
        $this->createProperty('code')
                ->setLabel('system.label.code')
                ->setRequired(TRUE)
                ->setUpdateable(FALSE)
                ->setLength(50)
                ->setInputType('textbox')
                ->addRule(new Soul_Validation_Rule_Character());
        $this->createProperty('name', 'string')
                ->setLabel('system.label.name')
                ->setLength(50)
                ->setRequired(TRUE)
                ->setInputType('textbox');
        $this->createProperty('description', 'string')
                ->setLabel('system.label.description')
                ->setLength(100)
                ->setInputType('textbox');
    }
}